let pageSize = 5;
let page = 1;
const creator = $.cookie("studentName");
let totalData = 0;
let addQuill, editQuill; // 声明富文本编辑器实例

// 页面加载完成后初始化
$(document).ready(function() {

    // 初始化富文本编辑器
    initQuillEditors();

    // 绑定所有事件
    bindEvents();

    // 初始化数据
    showByPage();
    getCount();
});

// 初始化Quill富文本编辑器
function initQuillEditors() {
    addQuill = new Quill('#addQuill', {
        theme: 'snow'
    });
    editQuill = new Quill('#editQuill', {
        theme: 'snow'
    });
}

// 绑定所有页面事件
function bindEvents() {
    // 添加笔记按钮点击事件
    $('#addNoteBtn').click(function() {
        // 清空表单
        $('#noteTitle').val('');
        addQuill.setText('');
        // 显示模态框
        $('#addNoteModal').css('display', 'flex');
    });

    // 关闭添加笔记模态框
    $('#closeAddModal, #cancelAddNote').click(function() {
        $('#addNoteModal').css('display', 'none');
    });

    // 关闭修改笔记模态框
    $('#closeEditModal, #cancelEditNote').click(function() {
        $('#editNoteModal').css('display', 'none');
    });

    // 添加笔记表单提交
    $('#addNoteForm').submit(function(e) {
        e.preventDefault();
        let name = $('#noteTitle').val().trim()
        let content = addQuill.root.innerHTML

        $.ajax({
            url: "/ClassNote/AddNote",
            type: "post",
            dataType: "json",
            data: {
                name,
                content,
                creator
            },
            success: function(res) {
                console.log(res)
                if (res.code === 200) {
                    alert("添加成功");
                    $('#addNoteModal').css('display', 'none');
                    showByPage();
                    getCount();
                } else {
                    alert("添加失败：" + res.msg);
                }
            },
            error: function() {
                alert("添加笔记请求失败，请联系管理员");
            }
        });
    });

    // 编辑笔记按钮点击事件
    $(document).on('click', '.edit-btn', function() {
        const noteId = $(this).closest('tr').find('.note-id').text();
        // alert(noteId)
        // 获取笔记详情
        $.ajax({
            url: "/ClassNote/GetNoteById",
            type: "post",
            data: { id: noteId },
            success: function(res) {
                // console.log(res)
                if (res.code === 200) {
                    const note = res.data;
                    $('#editNoteId').val(note.id);
                    $('#editNoteTitle').val(note.name);
                    editQuill.root.innerHTML = note.content;
                    $('#editNoteModal').css('display', 'flex');
                } else {
                    alert("获取笔记详情失败：" + res.msg);
                }
            },
            error: function() {
                alert("获取笔记详情请求失败");
            }
        });
    });

    // 修改笔记表单提交
    $('#editNoteForm').submit(function(e) {
        e.preventDefault();

        $.ajax({
            url: "/ClassNote/UpdateNote",
            type: "post",
            dataType: "json",
            data: {
                id: $('#editNoteId').val(),
                name: $('#editNoteTitle').val().trim(),
                content: editQuill.root.innerHTML,
                creator
            },
            success: function(res) {
                if (res.code === 200) {
                    alert("修改成功");
                    $('#editNoteModal').css('display', 'none');
                    showByPage();
                } else {
                    alert("修改失败：" + res.msg);
                }
            },
            error: function() {
                alert("修改笔记请求失败");
            }
        });
    });

    // 删除笔记按钮点击事件
    $(document).on('click', '.delete-btn', function() {
        const noteId = $(this).data('id');
        if (confirm("确定要删除这条笔记吗？")) {
            $.ajax({
                url: "/ClassNote/DeleteNote",
                type: "delete",
                data: { id: noteId },
                success: function(res) {
                    // console.log(res)
                    if (res.code === 200) {
                        showByPage();
                        getCount();
                    } else {
                        alert("删除失败：" + res.msg);
                    }
                },
                error: function() {
                    alert("删除笔记请求失败");
                }
            });
        }
    });

    // 生成试卷按钮点击事件
    $(document).on('click', '.exam-btn', function() {
        let loader = document.getElementById('compact-loader');
        let noteId = $(this).data('id');
        var name = $(this).parent().prev().text();
        var flag = false;
        $.ajax({
            url: "/exam/GetExamByName",
            type: "post",
            async:false,
            data: {
                name:name,
                creator:creator
            },
            success: function(res) {
                if (res.code === 200) {
                    flag = true;
                    showConfirm("该笔记的试卷已存在，是否要覆盖？",function(){
                        $.ajax({
                            url: "/ClassNote/GetNoteById",
                            type: "post",
                            data: { id:noteId },
                            success: function(res) {
                                // console.log("笔记详细信息" + res)
                                let name = res.data.name
                                let content = res.data.content
                                let creator = res.data.creator
                                let e_id
                                $.ajax({
                                    url:"/exam/deleteExam",
                                    type:"POST",
                                    async:false,
                                    data:{
                                        name
                                    },
                                    success:function(value){
                                        console.log("删除成功")
                                    },
                                })
                                $.ajax({
                                    url:"/ClassNote/AddExam",
                                    type:"post",
                                    data:{
                                        sid:$.cookie("student"),
                                        name,
                                        creator,
                                    },
                                    success:function(res){
                                        // console.log(res)
                                        e_id = res.data.id
                                        // alert("examId" + examId)
                                        console.log(loader)
                                        loader.style.display = 'flex';
                                        // 通过ai生成题目
                                        setTimeout(()=>{
                                            $.ajax({
                                                url:"/ClassNote/GenerateQuestion",
                                                type:"post",
                                                data:{
                                                    e_id,
                                                    content
                                                },
                                                success:function(res){
                                                    loader.style.display = "none";
                                                    $(".alert-success").show()
                                                    setTimeout(()=>{
                                                        $(".alert-success").hide()
                                                    },1200)
                                                    console.log(res)
                                                },
                                                error:function(){
                                                    $("#error-message").html("生成试卷失败")
                                                    $(".alert-danger").show()
                                                    setTimeout(()=>{
                                                        $(".alert-danger").hide()
                                                    },1200)
                                                    loader.style.display = "none";
                                                }
                                            })
                                        },30)
                                    },
                                    error:function (){
                                        $("#error-message").html("添加试卷失败")
                                        $(".alert-danger").show()
                                        setTimeout(()=>{
                                            $(".alert-danger").hide()
                                        },1200)
                                        loader.style.display = "none";
                                    }
                                })
                            },
                            error: function() {
                                $("#error-message").html("获取笔记详情失败")
                                $(".alert-danger").show()
                                setTimeout(()=>{
                                    $(".alert-danger").hide()
                                },1200)
                                loader.style.display = "none";
                            }
                        });
                    },function(){
                        document.getElementById('confirmModal').style.display = "none";
                    })
                }
            }
        })
        if(!flag){
            $.ajax({
                url: "/ClassNote/GetNoteById",
                type: "post",
                data: { id:noteId },
                success: function(res) {
                    // console.log("笔记详细信息" + res)
                    let name = res.data.name
                    let content = res.data.content
                    let creator = res.data.creator
                    let e_id
                    $.ajax({
                        url:"/ClassNote/AddExam",
                        type:"post",
                        data:{
                            sid:$.cookie("student"),
                            name,
                            creator,
                        },
                        success:function(res){
                            // console.log(res)
                            e_id = res.data.id
                            // alert("examId" + examId)
                            console.log(loader)
                            loader.style.display = 'flex';
                            // 通过ai生成题目
                            setTimeout(()=>{
                                $.ajax({
                                    url:"/ClassNote/GenerateQuestion",
                                    type:"post",
                                    data:{
                                        e_id,
                                        content
                                    },
                                    success:function(res){
                                        loader.style.display = "none";
                                        $(".alert-success").show()
                                        setTimeout(()=>{
                                            $(".alert-success").hide()
                                        },1200)
                                        console.log(res)
                                    },
                                    error:function(){
                                        $("#error-message").html("生成试卷失败")
                                        $(".alert-danger").show()
                                        setTimeout(()=>{
                                            $(".alert-danger").hide()
                                        },1200)
                                        loader.style.display = "none";
                                    }
                                })
                            },30)
                        },
                        error:function (){
                            $("#error-message").html("添加试卷失败")
                            $(".alert-danger").show()
                            setTimeout(()=>{
                                $(".alert-danger").hide()
                            },1200)
                            loader.style.display = "none";
                        }
                    })
                },
                error: function() {
                    $("#error-message").html("获取笔记详情失败")
                    $(".alert-danger").show()
                    setTimeout(()=>{
                        $(".alert-danger").hide()
                    },1200)
                    loader.style.display = "none";
                }
            });
        }
        // 获取笔记详情

    });

    // 搜索功能
    $('#searchBtn').click(function() {
        const keyword = $('.search-notes').val().trim();
        searchNotes(keyword);
    });

    // 回车键搜索
    $('.search-notes').keypress(function(e) {
        if (e.which === 13) {
            const keyword = $(this).val().trim();
            searchNotes(keyword);
        }
    });

    // 页码按钮点击事件
    $(document).on("click", ".page-number .page-btn", function() {
        page = parseInt($(this).text());
        showByPage();
        updateActivePage();
    });

    // 上一页
    $(document).on("click", ".front", function() {
        if (page > 1) {
            page--;
            showByPage();
            updateActivePage();
        }
    });

    // 下一页
    $(document).on("click", ".next", function() {
        if (page < Math.ceil(totalData / pageSize)) {
            page++;
            showByPage();
            updateActivePage();
        }
    });

    // 首页
    $(document).on("click", ".first", function() {
        page = 1;
        showByPage();
        updateActivePage();
    });

    // 尾页
    $(document).on("click", ".end", function() {
        page = Math.ceil(totalData / pageSize) || 1;
        showByPage();
        updateActivePage();
    });

    // 页码跳转
    $(document).on("click", ".change", function() {
        const targetPage = parseInt($(".page-input").val());
        if (!isNaN(targetPage) && targetPage >= 1 && targetPage <= Math.ceil(totalData / pageSize)) {
            page = targetPage;
            showByPage();
            updateActivePage();
        } else {
            alert("请输入有效的页码");
        }
    });

    // 每页条数切换
    $(document).on("change", ".page-size-select", function() {
        pageSize = parseInt($(this).val());
        page = 1; // 重置为第一页
        showByPage();
        getCount();
    });
}

// 分页展示笔记
function showByPage() {
    $.ajax({
        url: "/ClassNote/ShowByPage",
        type: "get",
        dataType: "json",
        data: {
            page,
            pageSize,
            creator
        },
        success: function(res) {
            if (res.code === 200) {
                const arr = res.data;
                $(".tbody").empty();

                if (arr.length === 0) {
                    $(".tbody").append(`
                        <tr>
                            <td colspan="3" style="text-align: center;">暂无笔记数据</td>
                        </tr>
                    `);
                    return;
                }

                arr.forEach(item => {
                    $(".tbody").append(`
                        <tr>
                            <td class="note-id">${item.id}</td>
                            <td>${item.name}</td>
                            <td>
                                <button class="action-btn edit-btn" data-id="${item.id}">
                                    <i class="fas fa-edit"></i> 查看
                                </button>
                                <button class="action-btn delete-btn" data-id="${item.id}">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                                <button class="action-btn exam-btn" data-id="${item.id}">
                                    <i class="fas fa-file-alt"></i> 生成试卷
                                </button>
                            </td>
                        </tr>
                    `);
                });
            } else {
                alert("获取笔记列表失败：" + res.msg);
            }
        },
        error: function() {
            alert("展示笔记信息出错，请联系管理员");
        }
    });
}

// 获取笔记总数并生成分页按钮
function getCount() {
    $.ajax({
        url: "/ClassNote/GetNoteCount",
        type: "get",
        dataType: "json",
        data: { creator },
        success: function(res) {
            if (res.code === 200) {
                totalData = res.data;
                const totalPages = Math.ceil(totalData / pageSize) || 1;
                $(".page-number").empty();

                // 生成分页按钮
                for (let j = 1; j <= totalPages; j++) {
                    // 处理省略号逻辑（只显示前2页、后2页和当前页附近）
                    if (totalPages > 5) {
                        if (j > 2 && j < totalPages - 1 && j !== page && j !== page - 1 && j !== page + 1) {
                            if (j === 3) {
                                $(".page-number").append(`<span>...</span>`);
                            }
                            continue;
                        }
                    }

                    const activeClass = j === page ? "active" : "";
                    $(".page-number").append(`
                        <button class="page-btn ${activeClass}" data-page="${j}">${j}</button>
                    `);
                }
            } else {
                alert("获取笔记数量失败：" + res.msg);
            }
        },
        error: function() {
            alert("获取教案数量出错，请联系管理员");
        }
    });
}

// 更新分页按钮激活状态
function updateActivePage() {
    $(".page-btn").removeClass("active");
    $(`.page-btn[data-page="${page}"]`).addClass("active");
}

function showConfirm(message, yesCallback, noCallback) {
    const confirmModal = document.getElementById('confirmModal');
    const confirmContent = document.getElementById('confirmContent');
    const confirmYes = document.getElementById('confirmYes');
    const confirmNo = document.getElementById('confirmNo');
    const closeConfirmModal = document.getElementById('closeConfirmModal');
    // 设置提示内容
    confirmContent.textContent = message;

    console.log(11)
    // 显示模态框
    confirmModal.style.display = 'flex';

    // 设置按钮事件
    confirmYes.onclick = function() {
        confirmModal.style.display = 'none';
        if (yesCallback) yesCallback();
    };

    confirmNo.onclick = function() {
        confirmModal.style.display = 'none';
        if (noCallback) noCallback();
    };

    closeConfirmModal.onclick = function() {
        confirmModal.style.display = 'none';
        // if (noCallback) noCallback();
    };

    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == confirmModal) {
            confirmModal.style.display = 'none';
        }
    };
}
